package com.want.buss.interfaces.configuration;

import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.stereotype.Component;

import com.mongodb.MongoClientURI;

@Component
public class MongoTemplateConfig implements ObjectFactory {

	@Override
	public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {

		String db = null;
		String host = null;
		String username = null;
		String password = null;
		int port = 27017;
		Reference reference = (Reference) obj;
		Enumeration<RefAddr> props =  reference.getAll();
		while (props.hasMoreElements()) {
			RefAddr addr = (RefAddr) props.nextElement();
			String propName = addr.getType();
			String propValue = (String) addr.getContent();
			if (propName.equals("db")) {
				db = propValue;
			} else if (propName.equals("host")) {
				host = propValue;
			} else if (propName.equals("username")) {
				username = propValue;
			} else if (propName.equals("password")) {
				password = propValue;
			} else if (name.equals("port")) {
				try {
					port = Integer.parseInt(propValue);
				} catch (NumberFormatException e) {
					throw new NamingException("Invalid port value " + propValue);
				}
			}
		}
		System.out.println("MongoTemplateConfig getObjectInstance() host: " + host + ", db: " + db + ", username: " + username
				+ ", password: " + password);
		String uri = String.format("mongodb://%s:%s@%s:%d/%s", username, URLEncoder.encode(password, "UTF-8"), host, port, db);
		MongoClientURI mongoURI = new MongoClientURI(uri);
		MongoTemplate mongoTemplate = new MongoTemplate(new SimpleMongoDbFactory(mongoURI));
		return mongoTemplate;
	}
}